const { sys_ad, sys_sys_sys_ad_dtl } = require('../../middleware/baseModel');

module.exports = {
  'GET /sys_ad/index': async (ctx, next) => {
    const res = await sys_ad.findAll({
      include: [{
        association: sys_ad.associations.dtl,
        attributes: ['id', 'link', 'image_url']
      }]
    });
    return ctx.success(res);
  },
  'POST /sys_ad/add': async (ctx, next) => {
    let row = ctx.getBody();
    const res = await sys_ad.create(row);

    if (row.dtl && row.dtl.length > 0) {
      let dtls = row.dtl.map(p => {
        return {
          ad_id: res.id,
          ...p
        }
      })
      await sys_ad_dtl.bulkCreate(dtls)
    }

    return ctx.success(res);
  },
  'POST /sys_ad/edit': async (ctx, next) => {
    let row = ctx.getBody();
    let id = ctx.get('id');

    let delRes = await sys_ad_dtl.destroy({
      where: {
        ad_id: id
      }
    })


    if (row.dtl && row.dtl.length > 0) {
      let dtls = row.dtl.map(p => {
        return {
          ad_id: id,
          image_url: p.image_url,
          link: p.link
        }
      })
      await sys_ad_dtl.bulkCreate(dtls)
    }

    const resList = await sys_ad.update(row, {
      where: {
        id: id
      }
    });
    return ctx.success(resList);
  },
  'POST /sys_ad/del': async (ctx, next) => {
    let id = ctx.get('id');
    const res = await sys_ad.destroy({
      where: {
        id: id
      }
    });
    return ctx.success(res);
  },
}